
from django.views import View
from django import http
from django.db import DatabaseError
from django.contrib.auth import login, authenticate,logout
import json
import re
from users.models import User
# Create your views here.


class LoginView(View):
    def get(self,request):
        if request.user.is_authenticated:
            username = request.COOKIES.get('mobile')
            try:
                user = User.objects.get(mobile=request.user)
            except:
                return http.JsonResponse({'error':'用户不存在'})


            return http.JsonResponse(
                {"errno": "0",
                 "errmsg": "已登录",
                 "data":{
                     'name':username,
                     'user_id':user.id
                 }
                 }
            )
        else:

            return http.JsonResponse(
                {'"errno": "4001","errmsg": "未登录"'}
            )

    def post(self, request):
        json_dict = json.loads(request.body.decode())
        # 接收
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')



        # 验证
        # 1.非空
        if not all([password, mobile]):
            return http.HttpResponseForbidden('填写数据不完整')


        # 密码
        if not re.match('^[0-9A-Za-z]{5,20}$', password):
            return http.HttpResponseForbidden('密码为5-20个字符')

        # 手机号
        if not re.match('^1[3456789]\d{9}$', mobile):
            return http.HttpResponseForbidden('手机号错误')
        # if User.objects.filter(mobile=mobile).count() > 0:
        #     return http.HttpResponseForbidden('手机号存在')
        # 1.创建用户对象

        user = authenticate(

            password=password,
            username=mobile,
        )
        if user is None:
            return http.JsonResponse({'errmsg': '用户名不存在或账号密码错误'})

        # 2.状态保持
        login(request, user)

        response = http.JsonResponse({
            "errno": "0",
            "errmsg": "成功"
        })
        response.set_cookie('mobile', user.mobile, max_age=3600 * 24 * 15)

        return response

    def delete(self, request):

        # 清楚登录信息
        logout(request)
        # 退出登录，退出登录时重定向首页

        response = http.JsonResponse({"errno": "0", "errmsg": "已登出"})

        # 退出登录时删除cookie中session信息
        response.delete_cookie('mobile')
        # 返回响应
        return response


class RegisterView(View):
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        # 接收
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')

        phonecode = json_dict.get('phonecode')


        # 验证
        # 1.非空
        if not all([password, mobile, phonecode]):
            return http.HttpResponseForbidden('填写数据不完整')


        # 密码
        if not re.match('^[0-9A-Za-z]{5,20}$', password):
            return http.HttpResponseForbidden('密码为5-20个字符')
        # 确认密码
        # if password != password2:
        #     return http.HttpResponseForbidden('两个密码不一致')
        # 手机号
        if not re.match('^1[3456789]\d{9}$', mobile):
            return http.HttpResponseForbidden('手机号错误')
        # if User.objects.filter(mobile=mobile).count() > 0:
        #     return http.HttpResponseForbidden('手机号存在')
        # 1.创建用户对象
        try:
            user = User.objects.create_user(
                # phonecode=phonecode,
                username=mobile,
                password=password,
                mobile=mobile,
            )
        except DatabaseError:
            return http.JsonResponse({'register_errmsg':'注册失败'})

        # 2.状态保持
        login(request, user)

        return http.JsonResponse({
            "errno": "0",
            "errmsg": "注册成功"
        })





